package com.central.apps.service.impl;


import com.central.app.common.base.BaseHandler;
import com.central.app.common.cache.CfgRedisCache;
import com.central.app.common.feign.WorkflowClient;
import com.central.app.common.util.AppCommonUtil;
import com.central.app.common.util.DeptUtil;
import com.central.app.common.util.OpinionTaskFactory;
import com.central.app.dao.CommonDao;
import com.central.app.handler.factory.HandlerFactory;
import com.central.app.model.*;
import com.central.app.service.FlowCommonService;
import com.central.app.service.HandlerService;
import com.central.apps.dao.BizCustomDao;
import com.central.apps.entity.BizFlowConsult;
import com.central.apps.entity.BizFlowConsultDtl;
import com.central.apps.entity.BizFlowCountersign;
import com.central.apps.service.CustomizationService;
import com.central.apps.util.AppCommonExtUtil;
import com.central.bizcommon.log.LogManager;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.bizcommon.model.flow.FlowTask;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.exception.service.ServiceException;
import com.central.common.util.SysUserUtil;
import com.central.common.util.ToolUtil;
import com.central.common.web.PageResult;
import javafx.beans.binding.StringBinding;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class CustomizationServiceImpl implements CustomizationService {
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private BizCustomDao bizCustomDao;
    @Autowired
    private FlowCommonService flowCommonService;
    @Autowired
    private WorkflowClient workflowClient;
    @Autowired
    private CfgRedisCache cfgRedisCache;

    @Override
    public PageResult<Map<String, Object>> findPage(Map<String, Object> params, String sql) throws Exception {
        int page = 1;
        int limit = 10;
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null) {
            page = MapUtils.getInteger(params, "page");
            limit = MapUtils.getInteger(params, "limit");
        }

        String tableName = MapUtils.getString(params, "tableName");
        BizObject object = null;
        if (ToolUtil.isNotEmpty(tableName)) {
            object = cfgRedisCache.getCacheObject(tableName);
        }

        StringBuilder sqlSb = AppCommonExtUtil.setFindParams(object, sql, params, null);

        return handlerService.pageList(page, limit, sqlSb.toString());
    }

    @Override
    public void setCountersign(BizFlowCountersign bizFlowCountersign) throws Exception {
        if (bizFlowCountersign != null) {
            //查当前节点
            String app = bizFlowCountersign.getApp();
            Long bizId = bizFlowCountersign.getBizId();
            String nodeId = flowCommonService.findNodeId(app, bizId);
            if (StringUtils.isNotBlank(nodeId)) {
                bizFlowCountersign.setNodeId(nodeId);
            }

            // 删除历史会签信息
            handlerService.updateBySql("delete from biz_flow_countersign where app = '" + app + "' and biz_id = " + bizId + " and node_id = '" + nodeId + "'");

            // 插入会签人员信息
            bizCustomDao.insertCountersign(bizFlowCountersign);
        }else {
            throw new Exception("设置会签异常");
        }
    }

    /**
     * 设置意见审批配置信息
     *
     * @param bizFlowConsult
     * @throws Exception
     */
    @Override
    public void setConsult(BizFlowConsult bizFlowConsult) throws Exception {
        if (bizFlowConsult != null) {
            Integer id = bizFlowConsult.getId();
            // 组织意见征询配置信息
            String app = bizFlowConsult.getApp();
            Long bizId = bizFlowConsult.getBizId();

            // 查询流程业务数据
            Map<String, Object> param = new HashMap<>();
            param.put("app", app);
            param.put("bizId", bizId.toString());
            BizFlowApp bizFlowApp = flowCommonService.findCurrentTask(param);

            //查当前节点
            String nodeId = flowCommonService.findNodeId(app, bizId);
            if (StringUtils.isNotBlank(nodeId)) {
                bizFlowConsult.setNodeId(nodeId);
            }

            if (id == null || id == 0) {
                // 查询节点审批人
                List<Map<String, Object>> executors = flowCommonService.findNowExecutors(app, bizId);
                StringBuilder sb = new StringBuilder();
                if (CollectionUtils.isNotEmpty(executors)) {
                    for (Map<String, Object> executorMap : executors) {
                        sb.append(MapUtils.getString(executorMap, "username")).append(",");
                    }

                    sb.deleteCharAt(sb.length() - 1);
                    bizFlowConsult.setOldExecutors(sb.toString());
                } else {
                    throw new ServiceException("当前节点不存在审批人!");
                }

                bizFlowConsult.setCreateUser(SysUserUtil.getLoginAppUser().getUsername());
                // 插入意见征询配置信息并返回主键id
                bizCustomDao.insertConsult(bizFlowConsult);

                // 查询意见征询接收人信息
                List<Map<String, Object>> list = handlerService.findBySql("select id from biz_flow_consult_cfg where app = '" + app + "'"
                        + " and biz_id = " + bizId + " and node_id = '" + nodeId + "'");

                if (CollectionUtils.isNotEmpty(list)) {
                    id = MapUtils.getInteger(list.get(0), "id");
                }

                // 组织意见征询明细数据
                String consultUsers = bizFlowConsult.getConsultUsers();
                String consultUserIds = bizFlowConsult.getConsultUserIds();

                if (StringUtils.isNotEmpty(consultUserIds)) {
                    String[] conUserIdArray = consultUserIds.split(",");
                    String[] consultUserArray = consultUsers.split(",");

                    for (int i = 0; i < conUserIdArray.length; i++) {
                        BizFlowConsultDtl bizFlowConsultDtl = new BizFlowConsultDtl();
                        bizFlowConsultDtl.setConsultId(id);
                        bizFlowConsultDtl.setConsultUser(consultUserArray[i]);
                        bizFlowConsultDtl.setConsultUserId(conUserIdArray[i]);
                        bizFlowConsultDtl.setStatus("未反馈");

                        bizCustomDao.insertConsultDtl(bizFlowConsultDtl);
                    }
                } else {
                    throw new Exception("意见征询接收人为空");
                }

                // 删除节点执行人
                this.delMultiTaskCandidateuser(bizFlowApp.getProcInsId(), sb.toString());
                // 意见征询任务添加执行人
                flowCommonService.addMultiTaskCandidateuser(bizFlowApp.getProcInsId(), consultUserIds);

                // 记录流程记录到biz_flow_opinion表
                LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
                BizApp bizApp = cfgRedisCache.getCacheApp(app);
                BizObject bizObject = cfgRedisCache.getCacheObjByApp(app);
                BizFlowApp flowApp = flowCommonService.findCurrentTask(param);

                String procInsId = flowApp.getProcInsId();
                String subProcInsId = flowApp.getSubProcInsId();
                FlowTask flowTask = workflowClient.findTodoTask(loginAppUser.getUsername(), StringUtils.isNotEmpty(subProcInsId) ? subProcInsId : procInsId);

                FlowOpinion flowOpinion = new FlowOpinion();
                flowOpinion.setOpinion("开启意见征询");
                flowOpinion.setNodeName(flowTask.getName());
                flowOpinion.setTaskId(flowTask.getId());
                flowOpinion.setCreateTime(new Date());
                // 查询当前节点id
                procInsId = StringUtils.isNotEmpty(subProcInsId) ? subProcInsId : procInsId;
                String nowNodeId = workflowClient.findNowActId(procInsId);
                flowOpinion.setNodeId(nowNodeId);

                /*
                 * 处理流程流转状态
                 */
                flowOpinion.setDirection("1");

                // 设置流程流转状态(1:审批通过; 0:驳回; -1:结束;)
                flowOpinion.setFlag(false);
                flowOpinion.setEnd(false);

                BizFlowOpinion bizFlowOpinion = new BizFlowOpinion(flowOpinion);
                bizFlowOpinion.setApp(bizApp.getName());
                bizFlowOpinion.setObject(bizObject.getName());
                bizFlowOpinion.setBizid(bizId);
                bizFlowOpinion.setUserid(loginAppUser.getId());
                bizFlowOpinion.setUsername(loginAppUser.getUsername());
                bizFlowOpinion.setNickname(loginAppUser.getNickname());
                bizFlowOpinion.setFlag("1");
                LogManager.me().executeLog(OpinionTaskFactory.flowOpinion(bizFlowOpinion));
            } else {
                // 组织意见征询明细数据
                String consultUsers = bizFlowConsult.getConsultUsers();
                String consultUserIds = bizFlowConsult.getConsultUserIds();

                if (StringUtils.isNotEmpty(consultUserIds)) {
                    String[] conUserIdArray = consultUserIds.split(",");
                    String[] consultUserArray = consultUsers.split(",");

                    /*
                     * 开始处理删除接收人
                     */
                    StringBuilder sb = new StringBuilder();
                    for (String consultId : conUserIdArray) {
                        sb.append("'").append(consultId).append("',");
                    }
                    sb.deleteCharAt(sb.length() - 1);

                    // 查询意见征询删除的接收人
                    List<Map<String, Object>> list = handlerService.findBySql("select * from biz_flow_consult_dtl t where t.consultId = (select id from biz_flow_consult_cfg where app = '" + app + "'"
                            + " and biz_id = " + bizId + " and node_id = '" + nodeId + "') and consultUserId not in (" +sb.toString()+ ")");

                    if (CollectionUtils.isNotEmpty(list)) {
                        StringBuilder del = new StringBuilder();
                        StringBuilder delStr = new StringBuilder();
                        for (Map<String, Object> map : list) {
                            del.append(MapUtils.getString(map, "consultUserId")).append(",");
                            delStr.append("'").append(MapUtils.getString(map, "consultUserId")).append("',");
                        }
                        del.deleteCharAt(del.length() - 1);
                        delStr.deleteCharAt(delStr.length() - 1);

                        // 删除任务执行人
                        this.delMultiTaskCandidateuser(bizFlowApp.getProcInsId(), del.toString());
                        // 删除接收人
                        handlerService.findBySql("delete from biz_flow_consult_dtl where consultId = (select id from biz_flow_consult_cfg where app = '" + app + "'"
                                + " and biz_id = " + bizId + " and node_id = '" + nodeId + "') and consultUserId in (" +delStr.toString()+ ")");
                    }
                    /*
                     * 结束处理删除接收人
                     */

                    /*
                     * 开始处理新增接收人
                     */
                    sb = new StringBuilder();
                    for (int i = 0; i < conUserIdArray.length; i++) {
                        // 查询意见征询的接收人
                        list = handlerService.findBySql("select * from biz_flow_consult_dtl t where t.consultId = " + id + " and consultUserId = '" + conUserIdArray[i] + "'");

                        if (CollectionUtils.isEmpty(list)) {
                            BizFlowConsultDtl bizFlowConsultDtl = new BizFlowConsultDtl();
                            bizFlowConsultDtl.setConsultId(id);
                            bizFlowConsultDtl.setConsultUser(consultUserArray[i]);
                            bizFlowConsultDtl.setConsultUserId(conUserIdArray[i]);
                            bizFlowConsultDtl.setStatus("未反馈");

                            bizCustomDao.insertConsultDtl(bizFlowConsultDtl);

                            sb.append(conUserIdArray[i]).append(",");
                        }
                    }

                    if (StringUtils.isNotEmpty(sb.toString())) {
                        sb.deleteCharAt(sb.length() - 1);
                        // 意见征询任务添加执行人
                        flowCommonService.addMultiTaskCandidateuser(bizFlowApp.getProcInsId(), sb.toString());
                    }

                    // 更新意见征询配置
                    handlerService.updateBySql("update biz_flow_consult_cfg set consultUserIds = '" + consultUserIds + "', consultUsers = '" + consultUsers + "', " +
                            " isTimed = " + bizFlowConsult.getIsTimed() + ", timeDuration = " + bizFlowConsult.getTimeDuration() + ", " +
                            " consultDesc = '" + bizFlowConsult.getConsultDesc() + "' where id = " + id);
                } else {
                    throw new Exception("意见征询接收人为空");
                }
            }
        } else {
            throw new Exception("意见征询参数为空");
        }
    }

    /**
     * 获取意见征询配置信息
     *
     * @param app
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getConsult(String app, Long id) throws Exception {
        //查当前节点
        String nodeId = flowCommonService.findNodeId(app, id);

        // 查询意见征询接收人信息
        List<Map<String, Object>> list = handlerService.findBySql("select * from biz_flow_consult_cfg where app = '" + app + "'"
                + " and biz_id = " + id + " and node_id = '" + nodeId + "'");

        if (CollectionUtils.isNotEmpty(list)) {
           return list.get(0);
        }
        return null;
    }

    //获取下一个流程节点的代理人
    @Override
    public String getAgentType(Map<String, Object> params) throws Exception{
        String app = MapUtils.getString(params, "app");
        Long bizId = MapUtils.getLong(params, "bizId");
        String direction = MapUtils.getString(params, "direction");
        BizApp appinfo = cfgRedisCache.getCacheApp(app);
        BizObject object = cfgRedisCache.getCacheObjByApp(app);
        String handleclass = appinfo.getHandleclass();
        BaseHandler beanHandler = null;
        if (StringUtils.isNotBlank(handleclass)) {
            beanHandler = HandlerFactory.getBeanHandler(handleclass);
        }
        try {
            //获取下个节点
            String nodeId = "";
            String procInsId = bizCustomDao.getProcInsId(app, bizId);
            if (StringUtils.isNotBlank(procInsId)) {
                //获取下一流程节点   （同意的流程节点！！）
                FlowOpinion op = new FlowOpinion();
                op.setDirection(direction);
                op.setEnd(false);
                op.setFlag(true);
                if (beanHandler != null) {
                    String nowNodeId = workflowClient.findNowActId(procInsId);
                    //流程节点
                    FlowNode flowNode = new FlowNode();
                    flowNode.setId(nowNodeId);
                    //流程变量
                    HashMap<String, Object> hs = new HashMap<String, Object>();
                    //查询应用主表信息并添加到流程变量中
                    CommonModel commonModel = new CommonModel();
                    AppCommonUtil.setFindDetailsParams(commonModel, appinfo, object, bizId);
                    Map<String, Object> modelData = commonDao.findById(commonModel);
                    hs.putAll(modelData);
                    beanHandler.addFlowVar(app, bizId, flowNode, op, hs);
                    op.setVariables(hs);
                }
                List<String> nextNodeId = workflowClient.findNextNodeId(procInsId, op);
                nodeId = nextNodeId.get(0);
            }
            //获取流程id
            return bizCustomDao.getAgentType(app, bizId, nodeId);
        } catch (Exception e) {
            throw new Exception("设置会签异常");
        }
    }

    /**
     * 删除意见审批配置信息
     *
     * @param params
     * @throws Exception
     */
    public void delConsultUsers(Map<String, Object> params) throws Exception {
        String procInsId = MapUtils.getString(params, "procInsId");
        String app = MapUtils.getString(params, "app");
        Long bizId = MapUtils.getLong(params, "bizId");
        String currentUserId = MapUtils.getString(params, "currentUserId");

        if (StringUtils.isNotEmpty(currentUserId)) {
            // 删除任务执行人
            this.delMultiTaskCandidateuser(procInsId, currentUserId);
            return;
        }

        // 查询节点id
        String nodeId = flowCommonService.findNodeId(app, bizId);

        // 查询意见征询接收人信息
        List<Map<String, Object>> list = handlerService.findBySql("select consultUserIds from biz_flow_consult_cfg where app = '" + app + "'"
            + " and biz_id = " + bizId + " and node_id = '" + nodeId + "'");

        String consultUserIds = "";
        if (CollectionUtils.isNotEmpty(list)) {
            consultUserIds = MapUtils.getString(list.get(0), "consultUserIds");
        }

        if (StringUtils.isNotEmpty(consultUserIds)) {
            // 删除任务执行人
            this.delMultiTaskCandidateuser(procInsId, consultUserIds);
        }
    }

    /**
     * 判断是否存在意见征询信息
     *
     * @param params
     * @throws Exception
     */
    @Override
    public String judgeIsConsult(Map<String, Object> params) throws Exception {
        String app = MapUtils.getString(params, "app");
        Long bizId = MapUtils.getLong(params, "bizId");

        // 查询节点id
        String nodeId = flowCommonService.findNodeId(app, bizId);

        // 查询意见征询接收人信息
        List<Map<String, Object>> list = handlerService.findBySql("select id, consultDesc from biz_flow_consult_cfg where app = '" + app + "'"
                + " and biz_id = " + bizId + " and node_id = '" + nodeId + "'");

        if (CollectionUtils.isNotEmpty(list)) {
            return MapUtils.getString(list.get(0), "consultDesc");
        }
        return "";
    }

    /**
     * 判断意见征询配置信息
     *
     * @param params
     * @throws Exception
     */
    @Override
    public boolean judgeConsultFinished(Map<String, Object> params) throws Exception {
        String app = MapUtils.getString(params, "app");
        Long bizId = MapUtils.getLong(params, "bizId");

        // 查询节点id
        String nodeId = flowCommonService.findNodeId(app, bizId);

        // 查询意见征询接收人信息
        List<Map<String, Object>> list = handlerService.findBySql("select id from biz_flow_consult_cfg where status = 1 and app = '" + app + "'"
                + " and biz_id = " + bizId + " and node_id = '" + nodeId + "'");

        if (CollectionUtils.isNotEmpty(list)) {
            return true;
        }
        return false;
    }

    /**
     * 更新意见征询配置信息
     *
     * @param params
     * @throws Exception
     */
    @Override
    public void updateConsultInfo(Map<String, Object> params) throws Exception {
        String app = MapUtils.getString(params, "app");
        Long bizId = MapUtils.getLong(params, "bizId");
        String opinion = MapUtils.getString(params, "opinion");

        // 查询节点id
        String nodeId = flowCommonService.findNodeId(app, bizId);

        // 查询意见征询接收人信息
        List<Map<String, Object>> list = handlerService.findBySql("select id, consultDesc, oldExecutors, createUser from biz_flow_consult_cfg where app = '" + app + "'"
                + " and biz_id = " + bizId + " and node_id = '" + nodeId + "'");

        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, Object> map = list.get(0);
            Integer consultId = MapUtils.getInteger(map, "id");
            handlerService.updateBySql("update biz_flow_consult_dtl set status = '已反馈' where consultId = " + consultId + " and consultUserId = '" + SysUserUtil.getLoginAppUser().getUsername() + "'");

            //记录流程审批历史到biz_flow_opinion表
            LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
            BizApp bizApp = cfgRedisCache.getCacheApp(app);
            BizObject bizObject = cfgRedisCache.getCacheObjByApp(app);
            BizFlowApp flowApp = flowCommonService.findCurrentTask(params);

            String procInsId = flowApp.getProcInsId();
            String subProcInsId = flowApp.getSubProcInsId();

            // 查询意见明细是否存在未反馈
            list = handlerService.findBySql("select * from biz_flow_consult_dtl where status = '未反馈' and consultId = " + consultId);

            if (CollectionUtils.isEmpty(list)) {
                // 删除意见征询配置
                delConsultInfo(params);

                // 还原流程审批人
                String oldExecutors = MapUtils.getString(map, "oldExecutors");
                String createUser = MapUtils.getString(map, "createUser");
                flowCommonService.addMultiTaskCandidateuser(StringUtils.isNotEmpty(subProcInsId) ? subProcInsId : procInsId, oldExecutors);
                workflowClient.claimTask(StringUtils.isNotEmpty(subProcInsId) ? subProcInsId : procInsId, createUser);
            }

            // 删除意见审批配置信息
            params.put("currentUserId", SysUserUtil.getLoginAppUser().getUsername());
            params.put("procInsId", StringUtils.isNotEmpty(subProcInsId) ? subProcInsId : procInsId);
            delConsultUsers(params);

            FlowTask flowTask = workflowClient.findTodoTask(loginAppUser.getUsername(), StringUtils.isNotEmpty(subProcInsId) ? subProcInsId : procInsId);

            FlowOpinion flowOpinion = new FlowOpinion();
            flowOpinion.setOpinion("意见反馈: "+opinion);
            flowOpinion.setNodeName(flowTask.getName());
            flowOpinion.setTaskId(flowTask.getId());
            flowOpinion.setCreateTime(new Date());
            // 查询当前节点id
            procInsId = StringUtils.isNotEmpty(subProcInsId) ? subProcInsId : procInsId;
            String nowNodeId = workflowClient.findNowActId(procInsId);
            flowOpinion.setNodeId(nowNodeId);

            /*
             * 处理流程流转状态
             */
            flowOpinion.setDirection("1");

            // 设置流程流转状态(1:审批通过; 0:驳回; -1:结束;)
            flowOpinion.setFlag(false);
            flowOpinion.setEnd(false);

            BizFlowOpinion bizFlowOpinion = new BizFlowOpinion(flowOpinion);
            bizFlowOpinion.setApp(bizApp.getName());
            bizFlowOpinion.setObject(bizObject.getName());
            bizFlowOpinion.setBizid(bizId);
            bizFlowOpinion.setUserid(loginAppUser.getId());
            bizFlowOpinion.setUsername(loginAppUser.getUsername());
            bizFlowOpinion.setNickname(loginAppUser.getNickname());
            bizFlowOpinion.setFlag("1");
            LogManager.me().executeLog(OpinionTaskFactory.flowOpinion(bizFlowOpinion));
        }
    }

    /**
     * 删除意见征询配置信息
     *
     * @param params
     * @throws Exception
     */
    public void delConsultInfo(Map<String, Object> params) throws Exception {
        String app = MapUtils.getString(params, "app");
        Long bizId = MapUtils.getLong(params, "bizId");

        // 查询节点id
        String nodeId = flowCommonService.findNodeId(app, bizId);

        // 查询意见征询接收人信息
        List<Map<String, Object>> list = handlerService.findBySql("select id from biz_flow_consult_cfg where app = '" + app + "'"
                + " and biz_id = " + bizId + " and node_id = '" + nodeId + "'");

        if (CollectionUtils.isNotEmpty(list)) {
            Integer consultId = MapUtils.getInteger(list.get(0), "id");
            handlerService.updateBySql("delete from biz_flow_consult_dtl where consultId = " + consultId);
            handlerService.updateBySql("delete from biz_flow_consult_cfg where id = " + consultId);
        }
    }

    @Override
    public String getCurrentAgentType(Map<String, Object> params) throws Exception {
        String app = MapUtils.getString(params, "app");
        Long bizId = MapUtils.getLong(params, "bizId");
        try {
            //获取流程实例id
            String procInsId = bizCustomDao.getProcInsId(app, bizId);
            if (StringUtils.isNotBlank(procInsId)) {
                //获取当前节点
                String nowNodeId = workflowClient.findNowActId(procInsId);
                // 获取当前代理人类型
                return bizCustomDao.getAgentType(app, bizId, nowNodeId);
            }
        } catch (Exception e) {
            throw new Exception("查询当前代理人类型异常");
        }

        return "-2";
    }

    @Override
    public Map<String, Object> btnJudgeLogic(String app, Long id) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("app", app);
        params.put("bizId", id);

        Map<String, Object> map = new HashMap<>();
        map.put("isStart", "false");
        map.put("isEnd", "false");
        map.put("isPause", "false");
        map.put("isCancelled", "false");
        map.put("isPromoter", "false");
        map.put("isConsulted", "false");
        map.put("isConsultFinished", "false");
        map.put("isConsultPromoter", "false");
        map.put("isTaskClaimed", "false");
        map.put("isExecutor", "false");
        map.put("isReturnInitNode", "false");


        // 流程是否已关闭
        boolean isEnd = flowCommonService.isEnd(app, id);
        map.put("isEnd", String.valueOf(isEnd));

        if (isEnd) {
            return map;
        }

        // 流程是否已开启
        try {
            String nodeId = flowCommonService.findNodeId(app, id);

            if (StringUtils.isNotEmpty(nodeId)) {
                map.put("isStart", "true");
            }

            // 是否已挂起
            boolean isPause = flowCommonService.isPause(app, id);
            map.put("isPause", String.valueOf(isPause));

            if (isPause) {
                return map;
            }

            // 当前用户是否可以审批
            boolean isExecutor = flowCommonService.isExecute(app, id);
            map.put("isExecutor", String.valueOf(isExecutor));

            // 判断是否认领任务后认领任务
            if (isExecutor) {
                BizFlowApp flowApp = flowCommonService.findCurrentTask(params);
                workflowClient.claimTask(flowApp.getProcInsId(), SysUserUtil.getLoginAppUser().getUsername());
            }
        } catch (Exception e) {
            map.put("isStart", "false");
            return map;
        }

        BizObject bizObject = cfgRedisCache.getCacheObjByApp(app);
        Map<String, Object> bizMap = handlerService.findById(app, bizObject.getName(), id);
        String status = MapUtils.getString(bizMap, "status");

        if ("已作废".equals(status)) {
            map.put("isCancelled", "true");
            return map;
        }

        // 查询是否开启了意见征询
        String result = this.judgeIsConsult(params);
        boolean isConsulted = false;
        if (StringUtils.isNotEmpty(result)) {
            isConsulted = true;
            map.put("consultDesc", result);

            // 查询意见征询是否完成
            boolean isConsultFinished = this.judgeConsultFinished(params);
            map.put("isConsultFinished", String.valueOf(isConsultFinished));

            // 查询意见征询是否发起人
            if (!isConsultFinished) {
                boolean isConsultPromoter = this.isConsultPromoter(params);
                map.put("isConsultPromoter", String.valueOf(isConsultPromoter));
            }
        }
        map.put("isConsulted", String.valueOf(isConsulted));

        // 当前登录用户是否为流程发起人
        boolean isPromoter = flowCommonService.isPromoter(app, id);
        map.put("isPromoter", String.valueOf(isPromoter));

        // 任务是否已经认领并且是前一个节点的审批人
        boolean isTaskClaimed = flowCommonService.isTaskClaimed(app, id);
        map.put("isTaskClaimed", String.valueOf(isTaskClaimed));

        // 查询 当前应用数据(单据) 流程是否(返回)为初始节点【提交审批】
        boolean isReturnInitNode = flowCommonService.isSubmitNode(app, id);
        map.put("isReturnInitNode", String.valueOf(isReturnInitNode));

        // 查找当前代理人类型
        String agentType = this.getCurrentAgentType(params);
        map.put("agentType", agentType);

        return map;
    }

    /**
     * 判断意见征询执行人是否删除
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public String judgeConsultExecutors(Map<String, Object> params) throws Exception {
        String app = MapUtils.getString(params, "app");
        Long bizId = MapUtils.getLong(params, "bizId");
        String consultUserIds = MapUtils.getString(params, "consultUserIds");

        // 查询节点id
        String nodeId = flowCommonService.findNodeId(app, bizId);

        String[] consultIdArray = consultUserIds.split(",");
        StringBuilder sb = new StringBuilder();

        for (String consultId : consultIdArray) {
            sb.append("'").append(consultId).append("',");
        }
        sb.deleteCharAt(sb.length() - 1);

        // 查询意见征询已反馈信息的接收人
        List<Map<String, Object>> list = handlerService.findBySql("select * from biz_flow_consult_dtl t where t.consultId = (select id from biz_flow_consult_cfg where app = '" + app + "'"
                + " and biz_id = " + bizId + " and node_id = '" + nodeId + "') and status = '已反馈' and consultUserId not in (" +sb.toString()+ ")");

        if (CollectionUtils.isNotEmpty(list)) {
            sb = new StringBuilder();
            for (Map<String, Object> map : list) {
                sb.append(MapUtils.getString(map, "consultUser")).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append("等接收人已反馈信息, 不能删除!");
            return sb.toString();
        }
        return "";
    }

    @Override
    public PageResult<Map<String, Object>> findList(String app, Map<String, Object> params) throws Exception {
        String tableName = MapUtils.getString(params, "object");
        String deptFieldName = MapUtils.getString(params, "deptFieldName");
        String rootDeptCode = MapUtils.getString(params, "rootDeptCode");

        params.remove("tableName");
        params.remove("rootDeptCode");

        if (StringUtils.isNotEmpty(rootDeptCode)) {
            // 获取父子部门数据
            String deptCodeString = DeptUtil.getDeptString(rootDeptCode);

            if (StringUtils.isNotEmpty(deptCodeString)) {
                params.put(deptFieldName + "_where_in", deptCodeString.replaceAll(",", "、").replaceAll("'",""));
            }
        }

        return handlerService.findPage(app, tableName, params);
    }

    /**
     * 判断当前用户是否是意见征询发起人
     *
     * @param params
     * @return
     */
    public boolean isConsultPromoter(Map<String, Object> params) throws Exception {
        String app = MapUtils.getString(params, "app");
        Long bizId = MapUtils.getLong(params, "bizId");
        String currentUserId = SysUserUtil.getLoginAppUser().getUsername();

        // 查询节点id
        String nodeId = flowCommonService.findNodeId(app, bizId);

        // 查询意见征询发起人信息
        List<Map<String, Object>> list = handlerService.findBySql("select consultUserIds from biz_flow_consult_cfg where app = '" + app + "'"
                + " and biz_id = " + bizId + " and node_id = '" + nodeId + "' and createUser = '" +currentUserId+ "'");

        if (CollectionUtils.isNotEmpty(list)) {
            return true;
        }
        return false;
    }

    /**
     * 删除流程节点审批人
     *
     * @param procInsId
     * @param userIds
     * @throws Exception
     */
    private void delMultiTaskCandidateuser(String procInsId, String userIds) throws Exception {
        // 删除流程节点审批人
        flowCommonService.delMultiTaskCandidateuser(procInsId, userIds);
        // 更新流程任务认领人
        handlerService.updateBySql("update act_ru_task set ASSIGNEE_ = null  where PROC_INST_ID_ = '"+procInsId+"'");
    }
}
